/*
 * This file is part of the zlog Library.
 *
 * Copyright (C) 2011 by Hardy Simpson <HardySimpson1984@gmail.com>
 *
 * Licensed under the LGPL v2.1, see the file COPYING in base directory.
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
// #include <sys/wait.h>
#include <unistd.h>
// #include <syslog.h>
#include "syslog.h"
#include <pthread.h>


#define THREAD_NUM	5
pthread_t  tid[THREAD_NUM];



//int work(long loop_count)
void* work(void* ptr)
{
	long loop_count = (long*)ptr;
	while(loop_count-- > 0) {
		syslog(LOG_INFO, "loglog");
		printf("loglog %ld\n", loop_count);
	}
	return 0;
}

pid_t forkx(int index, long* count)
{
	//BOOL ret = CreateProcess(NULL, cCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si[index], &pi[index]);
	int ret = pthread_create(&(tid[index]), NULL, work, count);
	// printf("CreateProcess: ret = %d\n", ret);
	return ret;
}

pid_t wait(int *status, int index)
{
	// DWORD ret = WaitForSingleObject(pi[index].hProcess, INFINITE);
	// printf("WaitForSingleObject, ret = %d\n", ret);
	int ret = pthread_join(tid[index], NULL);
	return ret;
}

int test(long process_count, long loop_count)
{
	long i;
	//pid_t pid;
	pid_t pid[THREAD_NUM];

	for (i = 0; i < process_count; i++) {
		// pid = fork();
		pid[i] = forkx(i, &loop_count);
		if (pid < 0) {
			printf("fork fail\n");
		} else if(pid == 0) {
			// work(&loop_count);
			// return 0;
		}
	}

	for (i = 0; i < process_count; i++) {
		// pid = wait(NULL);
		pid[i] = wait(NULL, i);
	}

	return 0;
}


int main(int argc, char** argv)
{

	if (argc != 3) {
		fprintf(stderr, "test nprocess nloop");
		exit(1);
	}

	openlog(NULL, LOG_NDELAY|LOG_NOWAIT|LOG_PID, LOG_LOCAL0);

	test(atol(argv[1]), atol(argv[2]));

	
	return 0;
}
